package com.itheima.myutil.dateutil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class _myDateUtil {
    public _myDateUtil() {
    }

    // 按照默认的模式“yyyy-MM-dd HH:mm:ss”将日期对象格式化为字符串
    public  static String  dateToString(Date date){
        return dateToString(date,null);
    }
    // 按指定的模式将日期对象格式化为字符串
    public  static String  dateToString(Date date,String pattern){
        if(pattern ==null||"".equals(pattern)){
            pattern = "yyyy/MM/dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        String s = sdf.format(date);
        return s;
    }
    // 按照指定的模式将字符串解析为日期对象
    public static Date stringToDate(String dateStr,String pattern) throws ParseException {
        if(pattern == null || "".equals(pattern)){
            pattern = "yyyy/MM/dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        Date parse = sdf.parse(dateStr);
        return parse;
    }
    // 按照默认的模式“yyyy-MM-dd HH:mm:ss”将字符串解析为日期对象
    public static Date stringToDate(String dateStr) throws ParseException {
        return stringToDate(dateStr,null);
    }
    // 获取时间间隔的方法，返回的是毫秒值
    public static long milliSecondsBetween(Date date1,Date date2){
        long time1 = date1.getTime();
        long time2 = date1.getTime();
        return time1>time2?time1-time2:time2-time1;
    }
    // 获取时间间隔的方法，返回的是天
    public static long daysBetween(Date date1,Date date2){
        return milliSecondsBetween(date1,date2)/1000/3600/24;
    }
}
